<template>
  <div class="area-management">
    <ArtTableHeader
      :title="$t('wms.area.title')"
      :total="tableData.total"
      @refresh="handleRefresh"
      @add="handleAdd"
    >
      <template #search>
        <WmsAreaSearch @search="handleSearch" @reset="handleReset" />
      </template>
    </ArtTableHeader>

    <ArtTable
      :columns="columns"
      :data="tableData.list"
      :loading="tableLoading"
      :pagination="pagination"
      @page-change="handlePageChange"
      @selection-change="handleSelectionChange"
    >
      <template #warehouseName="{ row }">
        <span>{{ getWarehouseName(row.warehouseId) }}</span>
      </template>

      <template #status="{ row }">
        <ElTag :type="row.status === '1' ? 'success' : 'danger'">
          {{ row.status === "1" ? "启用" : "禁用" }}
        </ElTag>
      </template>

      <template #action="{ row }">
        <ElButton type="primary" link @click="handleEdit(row)">编辑</ElButton>
        <ElButton type="danger" link @click="handleDelete(row)">删除</ElButton>
      </template>
    </ArtTable>

    <!-- 新增/编辑弹窗 -->
    <WmsAreaDialog
      v-model:visible="dialogVisible"
      :form-data="currentRow"
      :is-edit="isEdit"
      @confirm="handleDialogConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useTable } from "@/composables/useTable";
import { WmsBasicService } from "@/api/wms/basicApi";
import { useWmsStore } from "@/store/modules/wms";
import WmsAreaSearch from "./components/WmsAreaSearch.vue";
import WmsAreaDialog from "./components/WmsAreaDialog.vue";
import type { WMS } from "@/types/wms";

defineOptions({ name: "AreaManagement" });

// 使用WMS store
const wmsStore = useWmsStore();

// 表格配置
const columns = [
  { type: "selection", width: 50 },
  { prop: "areaNo", label: "库区编号", width: 120 },
  { prop: "areaName", label: "库区名称", minWidth: 150 },
  {
    prop: "warehouseName",
    label: "所属仓库",
    width: 150,
    slot: "warehouseName",
  },
  { prop: "areaType", label: "库区类型", width: 100 },
  { prop: "capacity", label: "容量", width: 100 },
  { prop: "usedCapacity", label: "已用容量", width: 100 },
  { prop: "status", label: "状态", width: 80, slot: "status" },
  { prop: "createTime", label: "创建时间", width: 160 },
  { prop: "action", label: "操作", width: 120, slot: "action", fixed: "right" },
];

// 使用表格组合式函数
const {
  tableData,
  tableLoading,
  pagination,
  handlePageChange,
  handleSelectionChange,
  refreshTable,
} = useTable<WMS.AreaInfo>({
  fetchData: (params) => WmsBasicService.getAreaList(params),
  defaultPageSize: 20,
});

// 搜索参数
const searchParams = ref<WMS.AreaQueryParams>({});

// 弹窗相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const currentRow = ref<Partial<WMS.AreaInfo>>({});

// 获取仓库名称
const getWarehouseName = (warehouseId: number) => {
  const warehouse = wmsStore.warehouseMap[warehouseId];
  return warehouse?.warehouseName || "-";
};

// 搜索处理
const handleSearch = (params: WMS.AreaQueryParams) => {
  searchParams.value = params;
  refreshTable(params);
};

// 重置搜索
const handleReset = () => {
  searchParams.value = {};
  refreshTable();
};

// 刷新
const handleRefresh = () => {
  refreshTable(searchParams.value);
};

// 新增
const handleAdd = () => {
  currentRow.value = {};
  isEdit.value = false;
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row: WMS.AreaInfo) => {
  currentRow.value = { ...row };
  isEdit.value = true;
  dialogVisible.value = true;
};

// 删除
const handleDelete = async (row: WMS.AreaInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除库区"${row.areaName}"吗？`,
      "删除确认",
      { type: "warning" },
    );

    await WmsBasicService.deleteArea(row.id!);
    ElMessage.success("删除成功");
    refreshTable(searchParams.value);
  } catch (_error) {
    if (_error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 弹窗确认
const handleDialogConfirm = async (formData: WMS.AreaInfo) => {
  try {
    if (isEdit.value) {
      await WmsBasicService.updateArea(formData);
      ElMessage.success("更新成功");
    } else {
      await WmsBasicService.createArea(formData);
      ElMessage.success("创建成功");
    }

    dialogVisible.value = false;
    refreshTable(searchParams.value);
  } catch (error) {
    ElMessage.error(isEdit.value ? "更新失败" : "创建失败");
  }
};

// 初始化
onMounted(async () => {
  // 加载仓库数据
  await wmsStore.getWarehouseList();
  // 加载表格数据
  refreshTable();
});
</script>

<style lang="scss" scoped>
.area-management {
  padding: 20px;

  :deep(.art-table-header) {
    margin-bottom: 16px;
  }
}
</style>
